prerender 您所在的位置:网站首页 vue prerender-spa-plugin 案例 prerender

prerender

2024-04-14 06:51| 来源: 网络整理| 查看: 265

Prerender SPA Plugin

Flexible, framework-agnostic static site generation for sites and SPAs built with webpack.

npm version npm downloads Dependency Status js-standard-style license

NPM

About prerender-spa-plugin-next

👉 This is the stable 4.x version of prerender-spa-plugin-next based on puppeteer.

The goal of this plugin is to provide a simple prerendering solution that is easily extensible and usable for any site or single-page-app built with webpack.

Plugins for other task runners and build systems are planned.

Requirements

Currently this plugin only works with webpack 5 and requires the html-webpack-plugin to be setup

Installation

npm i -D prerender-spa-plugin-next

Examples

Framework-specific examples can be found in the examples/ directory.

Vanilla JS Vue.js 2 Simple Vue.js 2 Router React (Create React App) Angular (Angular CLI + Eject) Basic Usage (webpack.config.js) const path = require('path') const PrerenderSPAPlugin = require('prerender-spa-plugin-next') module.exports = { plugins: [ ... new PrerenderSPAPlugin({ // Required - Routes to render. routes: [ '/', '/about', '/some/deep/nested/route' ], }) ] } Advanced Usage (webpack.config.js) const path = require('path') const PrerenderSPAPlugin = require('prerender-spa-plugin-next') const Renderer = PrerenderSPAPlugin.PuppeteerRenderer module.exports = { plugins: [ ... new PrerenderSPAPlugin({ // Optional - The location of index.html indexPath: 'index.html', // Required - Routes to render. routes: [ '/', '/about', '/some/deep/nested/route' ], // Optional - Allows you to customize the HTML and output path before // writing the rendered contents to a file. // renderedRoute can be modified and it or an equivalent should be returned. // renderedRoute format: // { // route: String, // Where the output file will end up (relative to outputDir) // originalRoute: String, // The route that was passed into the renderer, before redirects. // html: String, // The rendered HTML for this route. // outputPath: String // The path the rendered HTML will be written to. // } postProcess (renderedRoute) { // Ignore any redirects. renderedRoute.route = renderedRoute.originalRoute // Basic whitespace removal. (Don't use this in production.) renderedRoute.html = renderedRoute.html.split(/>[\s]+ /dist/dir/special.html if (renderedRoute.route.endsWith('.html')) { renderedRoute.outputPath = path.join(__dirname, 'dist', renderedRoute.route) } return renderedRoute }, // Server configuration options. server: { // Normally a free port is autodetected, but feel free to set this if needed. port: 8001 }, renderer: require('@prerenderer/renderer-puppeteer'), // The actual renderer to use. (Feel free to write your own) // Available renderers: https://github.com/Tribex/prerenderer/tree/master/renderers //The options to pass to the renderer class's constructor rendererOptions: { // Optional - The name of the property to add to the window object with the contents of `inject`. injectProperty: '__PRERENDER_INJECTED', // Optional - Any values you'd like your app to have access to via `window.injectProperty`. inject: { foo: 'bar' }, // Optional - defaults to 0, no limit. // Routes are rendered asynchronously. // Use this to limit the number of routes rendered in parallel. maxConcurrentRoutes: 4, // Optional - Wait to render until the specified event is dispatched on the document. // eg, with `document.dispatchEvent(new Event('custom-render-trigger'))` renderAfterDocumentEvent: 'custom-render-trigger', // Optional - Wait to render until the specified element is detected using `document.querySelector` renderAfterElementExists: 'my-app-element', // Optional - Wait to render until a certain amount of time has passed. // NOT RECOMMENDED renderAfterTime: 5000, // Wait 5 seconds. // Optional - Cancel render if it takes more than a certain amount of time // useful in combination with renderAfterDocumentEvent as it will avoid waiting infinitely if the event doesn't fire timeout: 20000, // Cancel render if it takes more than 20 seconds // Other puppeteer options. // (See here: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions) headless: false // Display the browser window when rendering. Useful for debugging. } }) ] } const path = require('path') const PrerenderSPAPlugin = require('prerender-spa-plugin-next') module.exports = { // ... plugins: [ new PrerenderSPAPlugin({ // (REQUIRED) List of routes to prerender routes: [ '/', '/about', '/contact' ], rendererOptions: { // headless: false, renderAfterDocumentEvent: 'render-event', inject: {}, timeout: 10000, }, postProcess: function (context) { var titles = { '/': 'Home', '/about': 'Our Story', '/contact': 'Contact Us' } context.html = context.html.replace( /[^ /dist/dir/special.html if (context.route.endsWith('.html')) { context.outputPath = path.join(__dirname, 'dist', context.route) } } postProcess(context) { return someAsyncProcessing(context.html) .then((html) => { context.html = html; }); } Vue.js Notes

If you are having issues prerendering with Vue.js, try adding the data-server-rendered="true" attribute to your root app element. This will cause Vue to treat your current page as an already-rendered app and update it rather than completely rerendering the whole tree. You can add the attribute using postProcess or by manipulating the DOM with JavaScript prior prerendering with renderAfterDocumentEvent.

@prerenderer/renderer-puppeteer options Option Type Required? Default Description maxConcurrentRoutes Number No 0 (No limit) The number of routes allowed to be rendered at the same time. Useful for breaking down massive batches of routes into smaller chunks. inject Object No None An object to inject into the global scope of the rendered page before it finishes loading. Must be JSON.stringifiy-able. The property injected to is window['__PRERENDER_INJECTED'] by default. injectProperty String No __PRERENDER_INJECTED The property to mount inject to during rendering. renderAfterDocumentEvent String No None Wait to render until the specified event is fired on the document. (You can fire an event like so: document.dispatchEvent(new Event('custom-render-trigger')) renderAfterElementExists String (Selector) No None Wait to render until the specified element is detected using document.querySelector renderAfterTime Integer (Milliseconds) No None Wait to render until a certain amount of time has passed. skipThirdPartyRequests Boolean No false Automatically block any third-party requests. (This can make your pages load faster by not loading non-essential scripts, styles, or fonts.) consoleHandler function(route: String, message: ConsoleMessage) No None Allows you to provide a custom console.* handler for pages. Argument one to your function is the route being rendered, argument two is the Puppeteer ConsoleMessage object. [Puppeteer Launch Options] ? No None Any additional options will be passed to puppeteer.launch(), such as headless: false. @prerenderer/renderer-jsdom options Option Type Required? Default Description maxConcurrentRoutes Number No 0 (No limit) The number of routes allowed to be rendered at the same time. Useful for breaking down massive batches of routes into smaller chunks. inject Object No None An object to inject into the global scope of the rendered page before it finishes loading. Must be JSON.stringifiy-able. The property injected to is window['__PRERENDER_INJECTED'] by default. injectProperty String No __PRERENDER_INJECTED The property to mount inject to during rendering. renderAfterDocumentEvent String No None Wait to render until the specified event is fired on the document. (You can fire an event like so: document.dispatchEvent(new Event('custom-render-trigger')) renderAfterElementExists String (Selector) No None Wait to render until the specified element is detected using document.querySelector renderAfterTime Integer (Milliseconds) No None Wait to render until a certain amount of time has passed. Tips & Troubleshooting JS not firing before prerender?

If you have code that relies on the existence of (and you almost certainly do), simply run it in a callback to the DOMContentLoaded event: (Otherwise you'll find that prerender-spa-plugin-next will output the contents of your page before your JS runs.)

document.addEventListener('DOMContentLoaded', function () { // your code })

For example, if you're using Vue.js and mounting to a in :

const root = new Vue({ // ... }) document.addEventListener('DOMContentLoaded', function () { root.$mount('#app') }) Inline Styles

If you rely on inline CSS, i.e. you do not extract CSS from your bundle and, thus, experience duplicate CSS style tags, consider using extract-text-webpack-plugin to extract CSS into a separate file and then either inject CSS back into a template.html file using html-webpack-plugin or just call it as an external CSS file.

Either way, there will not be any unnecessary styles inside JS.

Caveats For obvious reasons, prerender-spa-plugin-next only works for SPAs that route using the HTML5 history API. index.html#/hash/route URLs will unfortunately not work. Whatever client-side rendering library you're using should be able to at least replace any server-rendered content or diff with it. For Vue.js 1 use replace: false on root components. For Vue.js 2 Ensure your root component has the same id as the prerendered element it's replacing. Otherwise you'll end up with duplicated content. Alternatives react-snap - Zero-configuration framework-agnostic prerendering. Does not depend on webpack. Handles a variety of edge-cases. snapshotify - An experimental prerenderer that performes a number of speed optimizations. presite - Minimal-configuration framework-agnostic prerendering. prerenderer - Pluggable prerendering library that prerender-spa-plugin-next v3+ is based on. License (MIT) Copyright (c) 2017 Chris Fritz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Maintainers Adrien Foulon


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有